package com.sky.aop;
import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author: 夏帮连
 * @date: 2025/06/12
 * @description:
 * @version: 1.0
 */
@Component
@Aspect
@Slf4j
public class AutoFillAop {
    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行公共字段填充");
        //获取方法上的注解类型
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        //获取当前被拦截方法的实体对象
        Object[] args = joinPoint.getArgs();
        Object arg=args[0];
        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据不同的操作类型，通过反射赋值
        Class<?> clazz = arg.getClass();
        Method updateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
        Method updateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
        if(operationType==OperationType.INSERT){
            Method createUser = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
            Method createTime = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
            createTime.invoke(arg,now);
            updateTime.invoke(arg,now);
            createUser.invoke(arg,currentId);
            updateUser.invoke(arg,currentId);
        }
        else if(operationType==OperationType.UPDATE){
            updateTime.invoke(arg,now);
            updateUser.invoke(arg,currentId);
        }
    }
}
